//index.js
//获取应用实例
var app = getApp();
var modal = require('../../utils/modal');
var request = require('../../utils/request');
var utils = require('../../utils/utils');
var addrMock = require('../../mock/addrPicker');
var mock = require('../../mock/mock');
var addrPicker = require('../../components/addrPicker/addrPicker');
var counter = require('../../components/counter/counter');
var storage = require('../../utils/storage');
var math = require('../../utils/math');
var pay = require('../../common/wxpay');
// var add = require('../widget/add');

var pageSetting = {
  callback: function (componentName) {
    switch (componentName) {
      case 'addrPicker':
        //选择地址之后的回调函数
        if (this.data.address.id != arguments[1].id || arguments[1].edit) {
          var setData = {};
          setData.address = this.data.address = arguments[1];
          setData.hasAddr = this.data.hasAddr = true;
          this.setFee(setData);
        }
        break;
      default:
        break;
    }
  },
  data: {
    showPage: 0,
    disabled: false,
    address: {
      final_address: '添加收货地址'
    },
    orderDetail: {}, //订单详情
    curActId: 0,//当前操作的活动Id    
    totalPrice: 0,
    totalPriceText: '',//订单总价文本
    maskShow: false,
    hasAddr: false,
    salesForm:'',   
    offOrderAddress:'',   //订单地址
    offOrderUser:'',      //订单用户
    offOrderPhone:'',    //订单手机号
    offProvinceId:'',
    offCityId:'',
    offOreaId:''
  },
  onLoad: function (options) {    
    modal.loading();
    var that = this;
    var optCartId = options.cart_id.split(',');
    var optActId = options.act_id.split(',');
    var optType = options.type.split(',');
    var optNum = options.num.split(',');
    if(options.sales_form == 1){
      var optSaleForm = options.sales_form.split(','); 
      var optOrderAddress = options.offline_order_address.split(',');
      var optOrderUser = options.offline_order_user.split(',');
      var optOrderPhone = options.offline_order_phone.split(',');
      var optProviceId = options.offline_province_id.split(',');
      var optCityId = options.offline_city_id.split(',');
      var optAreaId = options.offline_area_id.split(','); 
      that.setData({
        salesForm:optSaleForm ,
        offOrderAddress:optOrderAddress,
        offOrderUser:optOrderUser,
        offOrderPhone:optOrderPhone,
        offProvinceId:optProviceId,
        offCityId:optCityId,
        offOreaId:optAreaId
      })
      console.log(that.data.offOreaId);
    }
    
    
    
    var params = [];
    for (var i = 0; i < optCartId.length; i++) {
      var tempObject = {};
      tempObject.cart_id = optCartId[i];
      tempObject.act_id = optActId[i];
      tempObject.type = optType[i];
      tempObject.num = optNum[i];
      params.push(tempObject);
    }
    var paramsStr = JSON.stringify(params);
    /*********************/
    var formapData = paramsStr.replace(/'/g, '\"');
    request.post({
      path: '/wxapp_api/api'
    }, { 'dp:api:act:formapplyorder': { 'cart_param': formapData } })
      .then(function (res) {
        var retData = res['dp:api:act:formapplyorder'];
        if (retData.ret != 0) {
          modal.hidden();
          wx.navigateTo({
            url: "../error/error"
          })
          return false;
        }
        var setData = {};
        setData.showPage = that.data.showPage = 1;
        var orderDetail = retData['data'];
        for (var key in orderDetail) {
          if (that.data.curActId == 0) {
            setData.curActId = that.data.curActId = key;
          }
          orderDetail[key].shipping = JSON.parse(orderDetail[key].shipping);         
          orderDetail[key].shippingIndex = 0;
          //预售
          if (orderDetail[key].sell_type == '1') {
            var sellTime = orderDetail[key].presell_time.replace(/-/g, "/");
            var presellDate = new Date(sellTime);
            orderDetail[key].persellDateText = presellDate.getFullYear() + '年' + presellDate.getMonth() + '月' + presellDate.getDay() + '日';
          }
        }
        that.data.orderDetail = orderDetail;
        that.setFee(setData);
      })


    /*********************/
    /*获取默认地址*/
    this.wiiAddrPickerGetDefaultAddr({ 'wiiAddrPickerUseWxAddr': (options.sales_form == '1' ? false : true) }, function (res) {
      if (res != undefined) {
        that.data.address = res;
        that.data.hasAddr = true;
        var setData = {
          address: that.data.address,
          hasAddr: that.data.hasAddr
        };       
        that.setFee(setData);
      } else {
        that.data.hasAddr = false;
        that.setFee({hasAddr:false});
      }
    });
  },
  bindPay: function (options) {
    var that = this;
    if(that.data.salesForm !=1){
       if(!that.data.hasAddr){
      modal.toast('请选择地址');
      return false;
      } 
    }
    
    if (!that.data['disabled']) {
      that.data['disabled'] = true;
      var postData = {};//需要提交到数据
      var orderActData = [];//订单相关数据
      for (var i in that.data.orderDetail) { //遍历单品
        var dpData = that.data.orderDetail[i];
        var itemData = {};
        itemData.act_id = dpData.id;
        itemData.shipping_id = dpData.shipping[dpData.shippingIndex].id;
        itemData.list = [];
        for (var j = 0; j < dpData.list.length; j++) {
          itemData.list.push({ act_spec_id: dpData.list[j].type, cart_id: dpData.list[j].cart_id || 0, purchase_count: parseInt(dpData.list[j].num) });
        }
        orderActData.push(itemData);
      }
      postData.order_act = (JSON.stringify(orderActData)).replace(/'/g, '\"');
      if(that.data.salesForm==1){
          postData.order_form = that.data.salesForm[0]
          postData.province_id = that.data.offProvinceId[0];
          postData.city_id = that.data.offCityId[0];
          postData.area_id = that.data.offOreaId[0];
          postData.address = that.data.offOrderAddress[0];
          postData.name = that.data.offOrderUser[0];
          postData.complete_address = that.data.offOrderAddress[0];
          postData.phone = that.data.offOrderPhone[0];
      } else{
          postData.province_id = that.data.address.province_id;
          postData.city_id = that.data.address.city_id;
          postData.area_id = that.data.address.area_id;
          postData.address = that.data.address.addr;
          postData.name = that.data.address.real_name;
          postData.complete_address = that.data.address.final_address;
          postData.phone = that.data.address.mobile;
      }
      
      var data = {
        'dp:api:act:submitorder': postData
      }
      request.post({
        path: '/wxapp_api/api'
      }, data)
        .then(function (res) {
          var result = res['dp:api:act:submitorder'];
          if (result.ret != '0') {
            that.data['disabled'] = false;
            //modal.toast(result.msg);
            wx.navigateTo({
              url: "../error/error"
            })
            return false;
          } else {
            var orderId = res['dp:api:act:submitorder']['data']['orderid'];
            // wx.navigateTo({
            //   url: '../submit/submit?order_id=' + orderId+'&offlineSalesForm='+that.data.salesForm[0]
            // })
            pay.callwxPay(orderId, that.data.salesForm[0], function(){
              that.data.disabled = false;
            })
          }
          // that.data.disabled = false;
          that.setData({
            disabled: that.data.disabled
          });
        });
    }
  },
  //减少
  minusFun: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var skuIndex = parseInt(e.currentTarget.dataset.skuindex);
    var oldNum = parseInt(this.data.orderDetail[index].list[skuIndex].num);
    if (oldNum > 1) {
      this.data.orderDetail[index].list[skuIndex].num = oldNum - 1;
    }
    this.setFee({}, index);
  },
  //增加
  plusFun: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var skuIndex = parseInt(e.currentTarget.dataset.skuindex);
    var oldNum = parseInt(this.data.orderDetail[index].list[skuIndex].num);
    if (this.data.orderDetail[index].list[skuIndex].num < this.data.orderDetail[index].list[skuIndex].surplus_stock) {
      this.data.orderDetail[index].list[skuIndex].num = oldNum + 1;
    }
    this.setFee({}, index);
  },
  showShippingFn: function (e) {
    var that = this;
    that.data.curActId = parseInt(e.currentTarget.dataset.index);
    that.data.maskShow = true;
    that.setData({
      maskShow: that.data.maskShow,
      curActId: that.data.curActId,
    });
  },
  hidenShippingFn: function () {
    this.data.maskShow = false;
    this.setData({
      maskShow: this.data.maskShow
    });
  },
  seleShippingFn: function (e) {
    var idx = parseInt(e.currentTarget.dataset.index);
    this.data.orderDetail[this.data.curActId].shippingIndex = idx;
    var setData = {};
    setData.maskShow = this.data.maskShow = false;
    this.setFee(setData, this.data.curActId);
  },
  //活动actId 单个计算,无参 重新计算
  setFee: function (setData, actId) {
    var that = this;
    setData = setData || {};
    if (actId != undefined) {
      that.calculateActFee(actId);
    } else {
      that.data.totalPrice = 0;
      for (var aid in that.data.orderDetail) {
        that.data.orderDetail[aid].shippingFee = 0;
        that.data.orderDetail[aid].goodsAmount = 0;
        that.calculateActFee(aid);
      }
    }
    setData.orderDetail = that.data.orderDetail;
    setData.totalPriceText = that.data.totalPriceText = (that.data.totalPrice / 100).toFixed(2);
    that.setData(setData)
  },
  //计算单品的总价
  calculateActFee: function (actId) {    
    var that = this;
    var oldShippingFee = that.data.orderDetail[actId].shippingFee || 0;
    var oldGoodsAmount = that.data.orderDetail[actId].goodsAmount || 0;
    var goodsNum = 0;
    var newGoodsAmount = 0;
    var newShippingFee = 0;
    var shippingIndex = that.data.orderDetail[actId].shippingIndex;
    //计算规格数量和新的单品总价
    for (var i = 0; i < that.data.orderDetail[actId].list.length; i++) {
      goodsNum += parseInt(that.data.orderDetail[actId].list[i].num);
      newGoodsAmount += parseInt(that.data.orderDetail[actId].list[i].num * that.data.orderDetail[actId].list[i].show_price * 100);
    }
    //计算单品的运费
    var postageRule = that.data.orderDetail[actId].shipping[shippingIndex]; //用户选择的物流规则
    var cityId = that.data.address.city_id || 0; //用户选择的城市Id
    var inFreeArea = false;
    var freeText = '';
    //设置包邮和没有地址显示免邮费
    if (postageRule.type == 0 || !that.data.hasAddr) {      
      newShippingFee = 0;
    } else {
      var sign = false;//是否已经计算出结果
      //检查满邮      
      if (postageRule.is_free == 1) {               
        for (var i = 0; i < postageRule.free_postage.length; i++) {
          for (var provinceId in postageRule.free_postage[i].ids) {
            //provinceId == 0 为全国
            if (provinceId == 0 || (cityId != 0 && postageRule.free_postage[i].ids[provinceId].indexOf(String(cityId)) != -1)) {
              if (newGoodsAmount >= postageRule.free_postage[i].postage * 100) {//条件
                newShippingFee = 0;
                sign = true;
              } else {
                freeText = '（满' + postageRule.free_postage[i].postage + '元包邮）';
              }
              break;
            }
          }
          if (sign == true) {
            break;
          }
        }
      }      
      //检查指定地区
      if (cityId != 0 && !sign && postageRule.designated_postage && postageRule.designated_postage.length > 0) {//检查特殊地区 
        for (var j = 0; j < postageRule.designated_postage.length; j++) {
          for (var pId in postageRule.designated_postage[j].ids) {
            if (pId == 0 || postageRule.designated_postage[j].ids[pId].indexOf(String(cityId)) != -1) {
              var ptRule = postageRule.designated_postage[j].postage;
              newShippingFee = ptRule.begin_postage * 100 + (goodsNum - ptRule.begin > 0 ? Math.ceil((goodsNum - ptRule.begin) / ptRule.add) : 0) * ptRule.add_postage * 100;
              sign = true;
              break;
            }
          }
          if (sign == true) {
            break;
          }
        }
      }
      //使用默认运费
      if (!sign) {         
        var beginFee = postageRule.default.begin_postage * 100;
        var addFee = 0;
        if (goodsNum > postageRule.default.begin) {
          addFee = Math.ceil((goodsNum - postageRule.default.begin) / postageRule.default.add) * postageRule.default.add_postage * 100
        }
        newShippingFee = beginFee + addFee;
      }
    }
    //修改订单总价格 设置单品运费
    that.data.orderDetail[actId].shippingFee = newShippingFee;
    that.data.orderDetail[actId].shippingFeeText = (newShippingFee / 100).toFixed(2);
    that.data.orderDetail[actId].shippingFreeText = freeText;
    that.data.orderDetail[actId].goodsAmount = newGoodsAmount;
    that.data.totalPrice = that.data.totalPrice - oldGoodsAmount - oldShippingFee + newGoodsAmount + newShippingFee;
  },
  stopPropagation: function () {
    //catchtap 停止冒泡
  }
};

var addrPickerOption = {
  data: {
    wiiAddrPicker: {
      'addrPickerUrl': '/wxapp_api/api',
      'addrPickerKey': {
        'setDefault': 'self:uc_api:address:setDefault',
        'delAddr': 'self:uc_api:address:del',
        'getAddrList': 'self:uc_api:address:get',
        'addAddr': 'self:uc_api:address:add',
        'getCityInfo': 'self:uc_api:address:getCityInfo'
      }
    }
  }
};
utils.assign(pageSetting, addrPicker, addrPickerOption, counter);
Page(pageSetting);
